package com.example.xmhds_1.ws;

import com.alibaba.fastjson.JSONObject;
import com.example.xmhds_1.dto.UserChatDTO;
import com.example.xmhds_1.dto.GroupChatDTO;
import com.example.xmhds_1.dto.UserinfoChatDTO;
import com.example.xmhds_1.entity.ChatMessage;
import com.example.xmhds_1.service.ChatService;
import com.example.xmhds_1.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 聊天相关WebSocket处理类
 */
@Slf4j
@Component
public class ChatWebSocket {

    public static ChatService chatService;
    public static UserInfoService userInfoService;

    /**
     * 处理获取聊天列表请求
     *
     * 请求格式：
     * {
     *   "type": "getChatList",
     *   "username": "用户账号"
     * }
     *
     * 响应格式：
     * {
     *   "type": "getChatList",
     *   "success": true,
     *   "chatList": [{                    // 私聊列表
     *     "userInfo": {                   // 聊天对象信息
     *       "id": "用户ID",
     *       "username": "用户名",
     *       "accountId": "账号ID",
     *       "createTime": "创建时间",
     *       "updateTime": "更新时间",
     *       "deleted": 0
     *     },
     *     "latestMessages": [{            // 最近消息列表
     *       "from": "发送者ID",
     *       "content": "消息内容",
     *       "time": "发送时间",
     *       "read": false                 // 是否已读
     *     }],
     *     "unreadCount": 0,              // 未读消息数
     *     "lastMessageTime": "2024-01-13 20:00:00"  // 最后消息时间
     *   }],
     *   "groupList": [{                   // 群聊列表
     *     "groupId": "群ID",
     *     "groupName": "群名称",
     *     "latestMessages": [{            // 最近消息列表
     *       "from": "发送者ID",
     *       "content": "消息内容",
     *       "time": "发送时间"
     *     }],
     *     "unreadCount": 0,              // 未读消息数
     *     "lastMessageTime": "2024-01-13 20:00:00"  // 最后消息时间
     *   }]
     * }
     */
    public JSONObject handleGetChatList(JSONObject request, JSONObject response) {
        //获取用户账号
        String username = request.getString("username");
        if (username == null || username.isEmpty()) {
            response.put("success", false);
            response.put("message", "用户名不能为空");
            return response;
        }

        if (userInfoService == null) {
            log.error("UserInfoService未注入");
            response.put("success", false);
            response.put("message", "系统错误");
            return response;
        }

        //通过账号获取用户ID
        String userId = userInfoService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("success", false);
            response.put("message", "用户不存在");
            return response;
        }

        //log.info("处理获取聊天列表请求: userId={}", userId);

        try {
            //获取用户与好友的聊天记录
            List<UserChatDTO> chatList = chatService.getUserChatList(userId);
            response.put("success", true);
            response.put("chatList", chatList);
            log.info("获取聊天列表成功: userId={}, size={}", userId, chatList.size());
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取聊天列表失败");
            log.error("获取聊天列表失败: userId={}", userId, e);
        }
        /**
         * 获取聊天群
         */
        try {
            List<GroupChatDTO> groupList = chatService.getGroupChatList(userId);
            response.put("success", true);
            response.put("groupList", groupList);
            log.info("获取群聊列表成功: userId={}, size={}", userId, groupList.size());
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取群聊列表失败");
            log.error("获取群聊列表失败: userId={}", userId, e);
        }
        return response;
    }

    /**
     * 处理获取聊天记录请求
     *
     * 请求格式：
     * {
     *   "type": "getChatHistory",
     *   "user0": "用户0",
     *   "user1": "用户1"
     * }
     *
     * 响应格式：
     * {
     *   "type": "getChatHistory",
     *   "success": true,
     *   "data": {
     *     "messages": [{
     *       "from": "发送者ID",
     *       "content": "消息内容",
     *       "time": "发送时间"
     *     }]
     *   }
     * }
     */
    public JSONObject handleGetChatHistory(JSONObject request, JSONObject response) {
        String user0 = request.getString("user0");
        String user1 = request.getString("user1");
        //log.info("处理获取聊天记录请求: user0={}, user1={}", user0, user1);

        try {
            ChatMessage chatHistory = chatService.getChatHistory(user0, user1);
            response.put("success", true);
            response.put("data", chatHistory);
            log.info("获取聊天记录成功: user0={}, user1={}", user0, user1);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取聊天记录失败");
            log.error("获取聊天记录失败: user0={}, user1={}", user0, user1, e);
        }

        return response;
    }

    /**
     * 处理发送消息请求
     *
     * 请求格式：
     * {
     *   "type": "sendMessage",
     *   "from": "发送者ID",
     *   "to": "接收者ID",
     *   "content": "消息内容"
     * }
     *
     * 响应格式：
     * {
     *   "type": "sendMessage",
     *   "success": true,
     *   "message": "发送成功"
     * }
     */
    public JSONObject handleSendMessage(JSONObject request, JSONObject response) {
        String from = request.getString("from");
        String to = request.getString("to");
        String content = request.getString("content");
        //log.info("处理发送消息请求: from={}, to={}", from, to);

        try {
            boolean success = chatService.saveMessage(from, to, content);
            response.put("success", success);
            response.put("message", success ? "发送成功" : "发送失败");
            //log.info("发送消息{}: from={}, to={}", success ? "成功" : "失败", from, to);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "发送失败");
            log.error("发送消息失败: from={}, to={}", from, to, e);
        }

        return response;
    }

    /**
     * 处理获取群聊列表请求
     */
    public JSONObject handleGetGroupChatList(JSONObject request, JSONObject response) {
        String userId = request.getString("userId");
        //log.info("处理获取群聊列表请求: userId={}", userId);

        try {
            List<GroupChatDTO> groupList = chatService.getGroupChatList(userId);
            response.put("success", true);
            response.put("data", groupList);
            //log.info("获取群聊列表成功: userId={}, size={}", userId, groupList.size());
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取群聊列表失败");
            log.error("获取群聊列表失败: userId={}", userId, e);
        }

        return response;
    }
    /**
     * 根据用户账号和好友账号获取聊天记录
     * 请求格式：
     * {
     *     "type": "getChatHistory",
     *     "user0": "用户账号",
     *     "user1": "好友账号"
     * }
     * 响应格式：
     * {
     *    "type": "getChatHistory",
     *    "success": true,
     *    "data": [{
     *          "sender": "发送者账号",
     *          "time": "发送时间",
     *          "receiverRead": "接收者是否已读",
     *          "content": "消息内容"
     *          }]
     *
     *  }
     */
    public JSONObject handleGetGroupChatHistory(JSONObject request, JSONObject response) {
        String user0 = request.getString("user0");
        String user1 = request.getString("user1");
        //log.info("处理获取聊天记录请求: user0={}, user1={}", user0, user1);
        try {
            List<UserinfoChatDTO> chatHistory = chatService.getChatHistoryByUser(user0, user1);
            response.put("success", true);
            response.put("data", chatHistory);
        }catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取聊天记录失败");
            log.error("获取聊天记录失败: user0={}, user1={}", user0, user1, e);
        }
        return response;
    }
    /**
    * 根据用户账号和好友账号使当前用户已读
     * 请求格式：
     * {
     *    "type": "updateGroupChatRead",
     *    "user0": "用户账号",
     *    "user1": "好友账号"
     *    }
     *
     *响应格式：
     * {
     *    "type": "updateGroupChatRead",
     *    "success": true,
     *    "message": "已读消息成功"
     *    }
     * {
     *      "type": "updateGroupChatRead",
     *      "success": false,
     *      "message": "已读消息失败"
     * }
    */
    public JSONObject handleUpdateGroupChatRead(JSONObject request, JSONObject response) {
        String user0 = request.getString("user0");
        String user1 = request.getString("user1");
        //log.info("已读消息请求: user0={}, user1={}", user0, user1);
        try {
            chatService.updateChatHistoryByUser(user0, user1);
            response.put("success", true);
            response.put("message", "已读消息成功");
        }catch (Exception e) {
            response.put("success", false);
            response.put("message", "已读消息失败");
            log.error("已读消息失败: user0={}, user1={}", user0, user1, e);
        }
        return response;

    }
    /**
     * 用户与好友,发送消息
     * 请求格式：
     * {
     *    "type": "sendGroupChat",
     *    "user0": "用户账号",
     *    "user1": "好友账号",
     *    "content": "消息内容"
     * }
     * 响应格式：
     * {
     *      "type": "sendGroupChat",
     *      "success": true,
     *      "message": "发送消息成功"
     * }
     * {
     *      "type": "sendGroupChat",
     *      "success": false,
     *      "message": "发送消息失败"
     * }
     */
    public JSONObject handleSendGroupChat(JSONObject request, JSONObject response) {
        String user0 = request.getString("user0");
        String user1 = request.getString("user1");
        String content = request.getString("content");
        //log.info("发送消息请求: user0={}, user1={}, content={}", user0, user1, content);
        try {
            boolean pd=chatService.setMessages(user0, user1, content);
            response.put("success", pd);
            if(pd) {
                response.put("message", "发送消息成功");
            }else{
                response.put("message", "发送消息失败");
            }
        }catch (Exception e){
            response.put("success", false);
            response.put("message", "发送消息失败");
            log.error("发送消息失败: user0={}, user1={}, content={}", user0, user1, content, e);
            }
        return response;
    }
}
